﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using static LiMinCRMPlugin.InterfaceDocking.TransportationModel;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 运输审核插件
    /// </summary>
    /// <remarks>
    /// 功能：运输在创建审核后自动传到CRM。
    /// 创建人：mey
    /// 创建日期：2024.3.19
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("运输区域审核同步至CRM")]
    [HotUpdate]
    public class TransportationToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            //物料编码
            e.FieldKeys.Add("FNumber");
            //物料名称
            e.FieldKeys.Add("FName");
            //所属国家
            e.FieldKeys.Add("F_RDLV_Country");
            //省份
            e.FieldKeys.Add("F_RDLV_Province");
            //城市
            e.FieldKeys.Add("F_RDLV_City");

            //邮编
            e.FieldKeys.Add("F_RDLV_PostCode");

            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //同步备注
            e.FieldKeys.Add("FDescription");
            //国家
            e.FieldKeys.Add("F_RDLV_Country");
            //省份
            e.FieldKeys.Add("F_RDLV_Province");
            //城市
            e.FieldKeys.Add("F_RDLV_City");
            //邮编
            e.FieldKeys.Add("F_RDLV_PostCode");
            e.FieldKeys.Add("FCreatorId");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);

            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                DataTable dt = APISetting();
                string httpUrl = dt.Rows[0]["F_RDLV_URL"].ToString();
                string httpSystemId = dt.Rows[0]["F_RDLV_SystemId"].ToString();
                string httpPassword = dt.Rows[0]["F_RDLV_Password"].ToString();


                string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                string FID = Convert.ToString(entity["Id"]);//内码                      
                string Number = entity["Number"].ToString();//编码
                string UserAccount = "kd-jxy";//用户账号
                //DynamicObject User = entity["CreatorId"] as DynamicObject;//用户
                //if (User != null)
                //{
                //    UserAccount = Convert.ToString(User["UserAccount"]);
                //}
                string Name = entity["Name"].ToString();//名称
                string FDescription = entity["Description"].ToString();//描述

                DynamicObject Country = entity["F_RDLV_Country"] as DynamicObject;//国家
                string CountryNumber = "";//使用组织内码

                if (Country != null)
                {
                    CountryNumber = Convert.ToString(Country["FNumber"]);//国家名称

                }
                DynamicObject Province = entity["F_RDLV_Province"] as DynamicObject;//省份
                string ProvinceNumber = "";//使用组织内码

                if (Province != null)
                {
                    ProvinceNumber = Convert.ToString(Province["FNumber"]);//省份

                }
                DynamicObject City = entity["F_RDLV_City"] as DynamicObject;//城市
                string CityNumber = "";//使用组织内码

                if (City != null)
                {
                    CityNumber = Convert.ToString(City["FNumber"]);//城市

                }

                string PostCode = entity["F_RDLV_PostCode"].ToString();//邮编

                string JYZT = "正常";//这里判断是不是禁用

                if (this.FormOperation.Operation.ToUpper() == "FORBID")//禁用
                {
                    JYZT = "禁用";
                }
                else
                {
                    JYZT = "正常";
                }

                #region 插入更新赋值
                mainTable mainTable1 = new mainTable()
                {
                    bm = Number,
                    mc = Name,
                    ms = FDescription,
                    erpnm = FID,
                    yzbm = PostCode,
                    jyzt = JYZT,
                    gj = CountryNumber,
                    sf = ProvinceNumber,
                    cs = CityNumber
                };
                //操作人员信息
                operationinfo operationinfo1 = new operationinfo()
                {
                    operatorAbAb = UserAccount,
                    operationDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    operationTime = DateTime.Now.ToString("HH:mm:ss")
                };

                String currentTimeTamp = getTimestamp();
                String md5Source = httpSystemId + httpPassword + currentTimeTamp;
                String md5OfStr = Md5(md5Source).ToLower();


                Header header1 = new Header()
                {
                    systemid = httpSystemId,
                    currentDateTime = currentTimeTamp,
                    Md5 = md5OfStr
                };

                Data data = new Data()
                {
                    operationinfo = operationinfo1,
                    mainTable = mainTable1
                };

                List<Data> datas = new List<Data>();
                datas.Add(data);


                DataHeader dataHeader = new DataHeader()
                {
                    data = datas,
                    header = header1
                };
                var json = JsonConvert.SerializeObject(dataHeader);
                json = json.ToString().Replace("operatorAbAb", "operator");
                #endregion

                #region 查询赋值
                TransportationSelectModel.mainTable mainTable2 = new TransportationSelectModel.mainTable()
                {
                    bm = Number,
                };
                //操作人员信息
                TransportationSelectModel.operationinfo operationinfo2 = new TransportationSelectModel.operationinfo()
                {
                    operatorAbAb = UserAccount,

                };
                TransportationSelectModel.Header header2 = new TransportationSelectModel.Header()
                {
                    systemid = httpSystemId,
                    currentDateTime = currentTimeTamp,
                    Md5 = md5OfStr
                };
                TransportationSelectModel.DataHeader dataHeader1 = new TransportationSelectModel.DataHeader()
                {
                    operationinfo = operationinfo2,
                    mainTable = mainTable2,
                    header = header2
                };

                var jsonS = JsonConvert.SerializeObject(dataHeader1);
                jsonS = jsonS.ToString().Replace("operatorAbAb", "operator");
                #endregion

                //查询是否存在
                var httpJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/getDataByPK/query_Transportation_area", jsonS);

                var arrresult = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(httpJson);//转换
                var MainTable = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(arrresult["result"].ToString());//转换


                if (MainTable.Count == 0)//
                {

                    var AddJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/create_Transportation_area", json);

                    var Addresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(AddJson);//转换


                    if (Addresult.status == "1")
                    {
                        #region 运输区域写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "运输区域";
                        interfaceLog.FInvokeType = "运输区域新增";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = json.ToString();
                        interfaceLog.FReturnData = AddJson.ToString();
                        interfaceLog.FRequest = json.ToString();
                        interfaceLog.FReturn = AddJson.ToString();
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_Transportation set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = true,
                            Message = string.Format("运输区域数据上传成功！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);

                        #endregion
                    }
                    else
                    {
                        #region 运输区域写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "运输区域";
                        interfaceLog.FInvokeType = "运输区域新增";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = json.ToString();
                        interfaceLog.FReturnData = AddJson.ToString();
                        interfaceLog.FRequest = json.ToString();
                        interfaceLog.FReturn = AddJson.ToString();
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_Transportation set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);

                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("运输区域数据上传失败，请手工同步！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);


                        #endregion
                    }

                }
                else
                {
                    //cube / restful /interface/saveOrUpdateModeData/update_Transportation_area
                    var UpdateJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/update_Transportation_area", json);

                    var Updateresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(UpdateJson);//转换

                    if (Updateresult.status == "1")
                    {
                        #region 运输区域写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "运输区域";
                        interfaceLog.FInvokeType = "运输区域更新";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = json.ToString();
                        interfaceLog.FReturnData = UpdateJson.ToString();
                        interfaceLog.FRequest = json.ToString();
                        interfaceLog.FReturn = UpdateJson.ToString();
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_Transportation set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = true,
                            Message = string.Format("运输区域数据更新成功！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);
                        #endregion
                    }
                    else
                    {
                        #region 运输区域写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "运输区域";
                        interfaceLog.FInvokeType = "运输区域更新";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = json.ToString();
                        interfaceLog.FReturnData = UpdateJson.ToString();
                        interfaceLog.FRequest = json.ToString();
                        interfaceLog.FReturn = UpdateJson.ToString();
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_Transportation set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);

                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("运输区域数据上传失败，请手工同步！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);


                        #endregion
                    }

                }


            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting()
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface");
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];

        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


    }
}
